﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ITSupportPlatform
{
    public partial class SelectPerson : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadUsers();
            }

        }
        DAL.FounderOAResourceGroupEntities context = new DAL.FounderOAResourceGroupEntities();

        private void LoadUsers()
        {
            List<DAL.Org_Users> users = context.Org_Users.Where(x => x.DeptID.Value == new Guid("74661AB1-E55A-49E1-AB59-BD047227EC6C")).ToList();

            List<DAL.Org_Users> noHaveUsers = new List<DAL.Org_Users>();
            List<DAL.Org_Users> exsitUsers = new List<DAL.Org_Users>();
            List<DAL.ITSupport_InfomationGroup> infos = context.ITSupport_InfomationGroup.ToList();
            foreach (DAL.Org_Users item in users)
            {
                if (infos.Exists(x => x.uid == item.ID))
                    continue;
                noHaveUsers.Add(item);
            }
            infos = context.ITSupport_InfomationGroup.Where(x => x.GroupName == DDLGroups.SelectedItem.Value).ToList();
            foreach (DAL.ITSupport_InfomationGroup item in infos)
            {
                DAL.Org_Users user = context.Org_Users.Where(x => x.ID == item.uid).SingleOrDefault();
                if (user != null)
                {
                    exsitUsers.Add(user);
                }

            }
            CurrentUsers.DataSource = exsitUsers;
            CurrentUsers.DataTextField = "Name";
            CurrentUsers.DataValueField = "ID";
            CurrentUsers.DataBind();

            CanAddUsers.DataSource = noHaveUsers;
            CanAddUsers.DataTextField = "Name";
            CanAddUsers.DataValueField = "ID";
            CanAddUsers.DataBind();
        }

        protected void ButAdd_Click(object sender, EventArgs e)
        {
            foreach (ListItem item in CanAddUsers.Items)
            {
                if (item.Selected)
                {
                    context.ITSupport_InfomationGroup.AddObject(new DAL.ITSupport_InfomationGroup()
                    {
                        Id = Guid.NewGuid(),
                        uid = new Guid(item.Value),
                        GroupName = DDLGroups.SelectedItem.Value
                    });
                }
            }
            context.SaveChanges();
            LoadUsers();
        }

        protected void DDLGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadUsers();
        }
    }
}